package org.yystory.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yystory.dataobject.SequenceBriefObject;
import org.yystory.entity.Sequence;
import org.yystory.service.StoryService;
import org.yystory.utility.ErrorParser;

import com.alibaba.fastjson.JSON;

public class StorySequenceServlet extends HttpServlet {

	private static final long serialVersionUID = -2861584071810207893L;

	public StorySequenceServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	private void response(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			Sequence[] sequences = StoryService.sequences(id);
			List<SequenceBriefObject> list = new ArrayList<SequenceBriefObject>();
			for (Sequence sequence : sequences) {
				SequenceBriefObject object = new SequenceBriefObject();
				object.setEgg(sequence.getEgg());
				object.setFlower(sequence.getFlower());
				object.setLength(sequence.getLength());
				object.setSequenceId(sequence.getId());
				object.setOrder(sequence.getOrder());
				object.setDate(sequence.getDate());
				object.setUserId(sequence.getUserId());
				list.add(object);
			}
			response.getWriter().print(JSON.toJSONString(list));
			response.getWriter().close();
		} catch (Exception e) {
			response.getWriter().print(
					ErrorParser.parseError("StorySequenceServlet", e.getClass()
							.getName() + ":" + e.getMessage()));
			response.getWriter().close();
		}
	}

}
